import { EllipsisOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Dropdown, Space, Tag, Avatar, message, Modal } from 'antd';
import { useRef, useCallback, useState } from 'react';
import { getNotices, removeUser } from '@/services/ant-design-pro/api';

export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

export default () => {
  const actionRef = useRef<ActionType>();
  const [editableKeys, setEditableKeys] = useState<React.Key[]>([]);

  // 删除用户的函数 - 只使用用户ID
  const handleDeleteUser = useCallback(async (userId: number) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户ID为 ${userId} 的用户吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          message.loading('正在删除用户...', 0);
          const result = await removeUser(userId);

          if (result) {
            message.destroy();
            await message.success('用户删除成功');
            // 自动刷新表格数据
            actionRef.current?.reload();
          } else {
            message.destroy();
            await message.error('用户删除失败');
          }
        } catch (error) {
          message.destroy();
          await message.error('删除用户时发生错误');
          console.error('删除用户失败:', error);
        }
      },
    });
  }, []);

  // 刷新数据的函数
  const handleRefresh = useCallback(async () => {
    try {
      message.loading('正在刷新数据...', 0);
      await actionRef.current?.reload();
      message.destroy();
      await message.success('数据刷新成功');
    } catch (error) {
      message.destroy();
      await message.error('数据刷新失败');
      console.error('刷新数据失败:', error);
    }
  }, []);

  // 批量删除用户
  const handleBatchDelete = useCallback(async (selectedRowKeys: React.Key[]): Promise<void> => {
    if (selectedRowKeys.length === 0) {
      await message.warning('请先选择要删除的用户');
      return;
    }

    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个用户吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          message.loading(`正在删除 ${selectedRowKeys.length} 个用户...`, 0);

          // 批量删除用户 - 使用 Promise.allSettled 处理部分失败的情况
          const deletePromises = selectedRowKeys.map((key) =>
            removeUser(Number(key))
          );

          const results = await Promise.allSettled(deletePromises);
          const successCount = results.filter(result =>
            result.status === 'fulfilled' && result.value
          ).length;

          message.destroy();

          if (successCount === selectedRowKeys.length) {
            await message.success(`成功删除 ${successCount} 个用户`);
          } else {
            await message.warning(`成功删除 ${successCount} 个用户，${selectedRowKeys.length - successCount} 个删除失败`);
          }

          // 自动刷新表格数据
          actionRef.current?.reload();
        } catch (error) {
          message.destroy();
          await message.error('批量删除用户时发生错误');
          console.error('批量删除用户失败:', error);
        }
      },
    });
  }, []);

  const handleCopyUser = useCallback(async (record: API.CurrentUser): Promise<void> => {
    const userInfo = `用户名: ${record.username}, 账号: ${record.userAccount}, 邮箱: ${record.email}`;
    try {
      await navigator.clipboard.writeText(userInfo);
      await message.success('用户信息已复制到剪贴板');
    } catch {
      await message.error('复制失败，请手动复制');
    }
  }, []);

  // 将 columns 定义移到组件内部
  const columns: ProColumns<API.CurrentUser>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 80,
      search: false,
      align: 'center',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      copyable: true,
      ellipsis: true,
      align: 'center',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '用户名是必填项',
          },
        ],
      },
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      copyable: true,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '用户角色',
      dataIndex: 'userRole',
      valueType: 'select',
      valueEnum: {
        0: { text: '普通用户', status: 'Default' },
        1: { text: '管理员', status: 'Processing' },
      },
      align: 'center',
      width: 90,
      fieldProps: {
        style: { width: 80 },
      },
      render: (_, record) => (
        <Tag color={record.userRole === 1 ? 'red' : 'blue'}>
          {record.userRole === 1 ? '管理员' : '普通用户'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'userStatus',
      valueType: 'select',
      valueEnum: {
        0: { text: '正常', status: 'Success' },
        1: { text: '禁用', status: 'Error' },
      },
      width: 80,
      align: 'center',
      fieldProps: {
        style: { width: 60 },
      },
    },
    {
      title: '头像',
      dataIndex: 'avatarUrl',
      search: false,
      width: 60,
      align: 'center',
      render: (_, record) => (
        <Avatar src={record.avatarUrl} size={24}>
          {record.username?.charAt(0)?.toUpperCase()}
        </Avatar>
      ),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      copyable: true,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      copyable: true,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      valueType: 'select',
      valueEnum: {
        0: { text: '女', status: 'Default' },
        1: { text: '男', status: 'Processing' },
      },
      width: 60,
      align: 'center',
      fieldProps: {
        style: { width: 50 },
      },
      render: (_, record) => (
        <span>{record.gender === 1 ? '男' : '女'}</span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      hideInTable: true,
      align: 'center',
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      width: 150,
      render: (_, record, __, action) => {
        if (editableKeys.includes(record.id)) {
          return null;
        }
        return (
          <Space style={{ minWidth: 100, whiteSpace: 'nowrap' }}>
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.id);
              }}
            >
              编辑
            </a>
            <a
              key="copy"
              onClick={() => handleCopyUser(record)}
            >
              复制
            </a>
            <a
              key="delete"
              style={{ color: 'red' }}
              onClick={() => handleDeleteUser(record.id)}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  return (
    <ProTable<API.CurrentUser>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async (params, sort, filter) => {
        console.log('请求参数:', params, sort, filter);
        await waitTime(1000);

        try {
          // 使用 getNotices 函数获取用户数据
          const response = await getNotices();
          console.log('获取到的用户数据:', response);

          // 处理不同的返回数据格式
          let userData: API.CurrentUser[] = [];
          let total = 0;

          if (response?.data) {
            // 如果返回的是分页格式 { data: { records: [], total: number } }
            if (response.data.records && Array.isArray(response.data.records)) {
              userData = response.data.records;
              total = response.data.total || userData.length;
            }
            // 如果返回的是数组格式 { data: [] }
            else if (Array.isArray(response.data)) {
              userData = response.data;
              total = userData.length;
            }
          }
          // 兼容直接返回数组的情况
          else if (Array.isArray(response)) {
            userData = response;
            total = userData.length;
          }

          // 返回符合 ProTable 要求的数据格式
          return {
            data: userData,
            total,
            success: true,
          };
        } catch (error) {
          console.error('获取用户数据失败:', error);
          return {
            data: [],
            total: 0,
            success: false,
          };
        }
      }}
      editable={{
        type: 'multiple',
        editableKeys,
        onChange: setEditableKeys,
        onSave: async (rowKey, data, row) => {
          console.log('保存编辑:', rowKey, data, row);
          await message.success('保存成功');
          // 编辑保存后也可以刷新数据
          actionRef.current?.reload();
        },
      }}
      rowSelection={{
        onChange: (selectedRowKeys, selectedRows) => {
          console.log('选中的用户:', selectedRowKeys, selectedRows);
        },
      }}
      columnsState={{
        persistenceKey: 'user-manage-table',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
          listsHeight: 400,
        },
        reload: false,
      }}
      form={{
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              createTime: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 10,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="用户管理"
      toolBarRender={(action, { selectedRowKeys }) => [
        <Button
          key="refresh"
          icon={<ReloadOutlined />}
          onClick={handleRefresh}
        >
          刷新
        </Button>,
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => {
            actionRef.current?.reload();
          }}
          type="primary"
        >
          新建用户
        </Button>,
        selectedRowKeys && selectedRowKeys.length > 0 && (
          <Button
            key="batchDelete"
            danger
            onClick={async () => await handleBatchDelete(selectedRowKeys)}
          >
            批量删除 ({selectedRowKeys.length})
          </Button>
        ),
        <Dropdown
          key="menu"
          menu={{
            items: [
              {
                label: '批量导入',
                key: '1',
              },
              {
                label: '批量导出',
                key: '2',
              },
              {
                label: '批量删除',
                key: '3',
                onClick: () => {
                  if (selectedRowKeys && selectedRowKeys.length > 0) {
                    handleBatchDelete(selectedRowKeys);
                  } else {
                    message.warning('请先选择要删除的用户');
                  }
                },
              },
            ],
          }}
        >
          <Button>
            <EllipsisOutlined />
          </Button>
        </Dropdown>,
      ]}
    />
  );
};
